import { addBatchAdvisorShift, getShiftList } from '@/api'
import { ShiftItemCell, DatePeriodSelect } from '@/components'
import { DefaultPagination } from '@/store/constant'
import { DatePeriod, ShiftItem } from '@/types/common'
import { SelectChangeEvent } from '@mui/material'

interface Props {
  refresh: () => void
  type: 'add'
  renderTrigger: (props: any) => React.ReactNode
  row: any
}
interface FormData {
  advisor_id: string
  shift_id: string
  start_date: string
  end_date: string
}
interface InputItemProps {
  formData: FormData[]
  setFormData: React.Dispatch<React.SetStateAction<FormData[]>>
  index: number
}
const ITEM_HEIGHT = 48

const InputItem = ({ formData, setFormData, index }: InputItemProps) => {
  const [params, setParams] = useState({
    size: DefaultPagination.pageSize,
    page: DefaultPagination.page + 1
  })
  const FORMATTER = 'YYYY-MM-DD'
  const defaultStart = dayjs()
  const defaultEnd = dayjs().add(1, 'week')
  const [datePeriod, setDatePeriod] = useState<DatePeriod>({
    start_date: defaultStart.format(FORMATTER),
    end_date: defaultEnd.format(FORMATTER)
  })
  const { data } = useRequest(() => getShiftList(params), {
    cacheKey: `/shift/list_${params.page}`,
    debounceWait: 500,
    refreshDeps: [params]
  })

  const handleChange = (event: SelectChangeEvent, index: number) => {
    let arr = [...formData]
    arr[index].shift_id = event.target.value
    setFormData(arr)
  }

  const list = (data?.data ?? []) as ShiftItem[]
  const changePage = (_e: any, page: number) => {
    const newParams = { ...params, page }
    setParams(newParams)
  }

  useEffect(() => {
    let arr = formData
    arr[index].start_date = datePeriod.start_date
    arr[index].end_date = datePeriod.end_date
    setFormData([...arr])
  }, [datePeriod.start_date, datePeriod.end_date])

  return (
    <>
      <FormControl fullWidth sx={{ marginBottom: '15px' }}>
        <InputLabel id="shift">班次</InputLabel>
        <Select
          required
          labelId="shift"
          id="shift"
          value={formData[index].shift_id}
          label="Age"
          onChange={(e) => handleChange(e, index)}
          MenuProps={{
            style: {
              maxHeight: ITEM_HEIGHT * 8
            }
          }}
        >
          <Grid container justifyContent="flex-end">
            <Pagination
              size="small"
              count={Math.ceil((data?.total ?? 0) / params.size)}
              variant="outlined"
              color="secondary"
              onChange={changePage}
            />
          </Grid>
          {list.map((item: ShiftItem, index) => {
            return (
              <MenuItem key={index} value={item.shift_id}>
                <ShiftItemCell index={index} item={item} />
              </MenuItem>
            )
          })}
        </Select>
      </FormControl>
      <DatePeriodSelect params={datePeriod} setParams={setDatePeriod} justifyContent="space-between" />
    </>
  )
}

const defaultFormData = {
  advisor_id: '',
  shift_id: '',
  start_date: '',
  end_date: ''
}

const handleConfig = {
  add: addBatchAdvisorShift
}

const BatchScheduleButton = ({ refresh, type = 'add', renderTrigger, row }: Props) => {
  const { advisor_id } = row
  const theme = useTheme()
  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))

  const [open, setOpen] = useState(false)
  const { run, loading } = useRequest(get(handleConfig, [type]), {
    manual: true,
    onSuccess() {
      refresh()
      setOpen(false)
      setFormData([{ ...defaultFormData }])
    }
  })
  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }
  const addInputItem = () => {
    if (formData.length < 3) {
      setFormData([...formData, { ...defaultFormData }])
    }
  }
  const handleDelete = (index: number) => {
    let arr = [...formData]
    arr.splice(index, 1)
    setFormData(arr)
  }

  const handleConfirm = () => {
    setOpen(false)
    formData.forEach((item) => {
      run({ ...item, advisor_id })
    })
  }
  const [formData, setFormData] = useState([{ ...{ ...defaultFormData } }])

  return (
    <>
      {renderTrigger({ onClick: handleOpen })}
      <Dialog
        fullWidth
        maxWidth="xs"
        fullScreen={fullScreen}
        open={open}
        onClose={handleClose}
        PaperProps={{
          component: 'form',
          onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
            event.preventDefault()
            handleConfirm()
          }
        }}
      >
        <DialogTitle fontSize="1rem">
          <Grid container justifyContent="space-between">
            <Grid>批量编辑</Grid>
            <Button variant="outlined" size="small" color="secondary" onClick={addInputItem}>
              新增班次
            </Button>
          </Grid>
        </DialogTitle>
        <DialogContent>
          <Stack spacing={3} direction="column" padding={2}>
            {formData.map((_item, index) => (
              <Card key={index}>
                <Divider></Divider>
                <Grid container justifyContent="space-between" mt={1} mb={2}>
                  <Chip
                    variant="outlined"
                    color="secondary"
                    label={`时间段${index + 1}`}
                    size="small"
                    sx={{ fontSize: '12px' }}
                  />
                  {formData.length > 1 && (
                    <Button
                      variant="contained"
                      color="error"
                      sx={{ height: '24px' }}
                      onClick={() => {
                        handleDelete(index)
                      }}
                    >
                      删除
                    </Button>
                  )}
                </Grid>
                <InputItem formData={formData} setFormData={setFormData} index={index} />
              </Card>
            ))}
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            Cancel
          </Button>
          <LoadingButton variant="contained" color="secondary" loading={loading} type="submit">
            应用
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default BatchScheduleButton
